#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <unistd.h>
#include <pthread.h>

using namespace std;

int tickets = 1000; // 用多线程模拟抢票
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;//全局初始化

class threadData
{
public:
    threadData(int number , pthread_mutex_t *mutex)
    {
        threadname = "线程-" + to_string(number);
        lock = mutex;
    }

public:
    string threadname;
    pthread_mutex_t *lock;
};

void *getTicket(void *args)
{
    threadData *td = static_cast<threadData *>(args);
    const char *name = td->threadname.c_str();
    while (true)
    {
        pthread_mutex_lock(td->lock); //申请锁
        pthread_cond_wait(&cond,td->lock);
        if(tickets > 0)
        {
            usleep(1000);
            printf("%s, 抢到一张票: %d\n", name, tickets);
            tickets--;
            pthread_mutex_unlock(td->lock);//释放锁
        }
        else{
            pthread_mutex_unlock(td->lock);//释放锁

            break;
        }
    }
    printf("%s 退出\n", name);
    return nullptr;
}

int main()
{
    pthread_mutex_t lock;//定义一个锁
    pthread_mutex_init(&lock, nullptr);//对该锁进行初始化

    vector<pthread_t> tids;
    vector<threadData *> thread_datas;
    for (int i = 1; i <= 3; i++)
    {
        pthread_t tid;
        threadData *td = new threadData(i ,&lock);
        thread_datas.push_back(td);
        //要将锁也传给线程
        pthread_create(&tid, nullptr, getTicket, thread_datas[i - 1]);
        tids.push_back(tid);
    }

    //等待线程
    for (auto thread : tids)
    {
        pthread_join(thread, nullptr);
    }
    //释放空间资源
    for (auto td : thread_datas)
    {
        delete td;
    }

    pthread_mutex_destroy(&lock);
    return 0;
}